package com.knowledge.business.service;

/**
 * @author: zhaoyongke
 * @create: 2025-09-09 11:09
 * @description: ChatService
 */

import com.knowledge.business.domain.ChatRequest;
import com.knowledge.business.domain.ChatResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

@Service
@Log4j2
public class ChatService {

    private static final String API_URL = "https://api.siliconflow.cn/v1/chat/completions";
    private static final String API_KEY = "sk-eoxdizwvwgyqlclcsbkmcisgpeuhepenwnbdhdskpvkwaufa";

    private static final String modelName = "Qwen/Qwen2.5-72B-Instruct";


    @Autowired
    private RestTemplate restTemplate;

    public ChatResponse createChatCompletion(String userContent) {

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + API_KEY);

        // 构建请求体
        ChatRequest.Message message = new ChatRequest.Message();
        message.setRole("user");
        message.setContent(userContent);

        ChatRequest request = new ChatRequest();
        request.setModel(modelName);
        request.setMessages(Collections.singletonList(message));

        HttpEntity<ChatRequest> requestEntity = new HttpEntity<>(request, headers);
        // 开始时间
        long startTime = System.currentTimeMillis();
        log.info("开始请求=======");
        // 发送请求并获取响应
        ChatResponse chatResponse = restTemplate.postForObject(API_URL, requestEntity, ChatResponse.class);
        // 结束时间
        long endTime = System.currentTimeMillis();
        log.info("请求耗时：" + (endTime - startTime) + "毫秒");
        return chatResponse;
    }
}
